package com.guomei.controller.curse;

import com.guomei.bean.User;
import com.guomei.bean.curse.ComputePrice;
import com.guomei.bean.curse.CourseOrder;
import com.guomei.bean.curse.CreateOrUpdateOrderDTO;
import com.guomei.service.curse.CourseOrderService;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 课程订单控制器
 */
@RestController
@RequestMapping("/api1/course-order")
@Slf4j
public class CourseOrderController {
    @Resource
    private CourseOrderService courseOrderService;


    /**
     * 根据条件查询订单
     */
    @PostMapping("/select")
    public Result<?> searchOrders(@RequestBody CourseOrder order) {
        log.info("根据条件查询订单：" + order);
        try {
            if (order == null || order.getPageNum() == null || order.getPageSize() == null){
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (order.getPageNum() <= 0 || order.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            
            // 强制只查询未删除的订单，忽略前端传入的 isDeleted 参数
            order.setIsDeleted(false);
            
            return courseOrderService.getByConditionWithCourse(order);
        } catch (Exception e) {
            log.info("查询订单信息失败",e);
            return Result.fail("查询订单信息失败");
        }
    }

    /**
     * 查询老师贩卖课程
     */
    @PostMapping("/selectTeacherOrder")
    public Result<?> selectTeacherOrder(@RequestBody User user) {
        log.info("查询老师贩卖课程：" + user);
        try {
            if (user == null || user.getPageNum() == null || user.getPageSize() == null){
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (user.getPageNum() <= 0 || user.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }

            return courseOrderService.selectTeacherOrder(user);
        } catch (Exception e) {
            log.info("查询订单信息失败",e);
            return Result.fail("查询订单信息失败");
        }
    }

    /**
     * 根据条件查询订单
     */
    @PostMapping("/selectByCourseList")
    public Result<?> selectByCourseList(@RequestBody CourseOrder order) {
        log.info("根据课程列表查询订单：" + order);
        try {
            if (order == null || order.getPageNum() == null || order.getPageSize() == null){
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (order.getPageNum() <= 0 || order.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }

            // 强制只查询未删除的订单，忽略前端传入的 isDeleted 参数
            order.setIsDeleted(false);

            return courseOrderService.getByCourseList(order);
        } catch (Exception e) {
            log.info("查询订单信息失败",e);
            return Result.fail("查询订单信息失败");
        }
    }
    /**
     * 计算订单价格
     */
    @PostMapping("/computePrice")
    public Result<?> computePrice(@Valid @RequestBody ComputePrice computePrice, BindingResult result) {
        log.info("计算订单价格：" + computePrice);
        //实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            return courseOrderService.computePrice(computePrice);
        } catch (Exception e) {
            log.info("计算订单价格失败",e);
            return Result.fail("计算订单价格失败");
        }
    }

    /**
     * 创建订单
     */
    @PostMapping("/createOrder")
    public Result<?> createOrder(@Valid @RequestBody CreateOrUpdateOrderDTO createOrUpdateOrderDTO, BindingResult result) {
        log.info("创建订单：" + createOrUpdateOrderDTO);
        //实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            CourseOrder order = new CourseOrder();
            order.setUserId(createOrUpdateOrderDTO.getUserId());
            order.setCourseId(createOrUpdateOrderDTO.getCourseId());
            order.setAmount(createOrUpdateOrderDTO.getAmount());
            order.setDiscountAmount(createOrUpdateOrderDTO.getDiscountAmount());
            order.setPayAmount(createOrUpdateOrderDTO.getPayAmount());
            order.setPayType(createOrUpdateOrderDTO.getPayType());
            order.setPayStatus(createOrUpdateOrderDTO.getPayStatus());
            order.setDistributionUserId(createOrUpdateOrderDTO.getDistributionUserId());
            order.setDistributionAmount(createOrUpdateOrderDTO.getDistributionAmount());
            order.setCreatedTime(createOrUpdateOrderDTO.getCreatedTime());
            order.setUpdatedTime(createOrUpdateOrderDTO.getUpdatedTime());
            order.setExpireTime(createOrUpdateOrderDTO.getExpireTime());
            order.setPayTime(createOrUpdateOrderDTO.getPayTime());
            order.setCouponId(createOrUpdateOrderDTO.getCouponId());
            if (createOrUpdateOrderDTO.getId() != null){
                order.setId(createOrUpdateOrderDTO.getId());

                return courseOrderService.update(order);
            }else {
                order.setPayStatus((short) 0);
                order.setOrderStatus((short) 2);
                return courseOrderService.createOrder(order);
            }
        } catch (Exception e) {
            log.info("创建订单失败",e);
            return Result.fail("创建订单失败");
        }
    }
    
    /**
     * 用户主动取消订单
     */
    @PostMapping("/cancel/{orderNo}")
    public Result<?> cancelOrderByUser(@PathVariable String orderNo) {
        log.info("用户主动取消订单，订单号：{}", orderNo);
        try {
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.fail("订单号不能为空");
            }
            
            // 验证订单是否存在
            CourseOrder order = courseOrderService.getByOrderNo(orderNo);
            if (order == null) {
                return Result.fail("订单不存在");
            }
            
            // 检查订单状态，只有未支付的订单才能取消
            if (order.getPayStatus() != null && order.getPayStatus() == 1) {
                return Result.fail("已支付的订单无法取消");
            }
            
            // 检查订单是否已经取消
            if (order.getPayStatus() == 2) {
                return Result.fail("订单已取消");
            }
            
            // 调用取消订单服务
            boolean success = courseOrderService.cancelOrder(orderNo);
            if (success) {
                log.info("用户主动取消订单成功，订单号：{}", orderNo);
                return Result.success("取消订单成功");
            } else {
                log.error("用户主动取消订单失败，订单号：{}", orderNo);
                return Result.fail("取消订单失败");
            }
            
        } catch (Exception e) {
            log.error("用户主动取消订单异常，订单号：{}", orderNo, e);
            return Result.fail("取消订单失败");
        }
    }
    
    /**
     * 根据订单号查询订单状态
     */
    @GetMapping("/status/{orderNo}")
    public Result<?> getOrderStatus(@PathVariable String orderNo) {
        log.info("查询订单状态，订单号：{}", orderNo);
        try {
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.fail("订单号不能为空");
            }
            
            CourseOrder order = courseOrderService.getByOrderNo(orderNo);
            if (order == null) {
                return Result.fail("订单不存在");
            }
            
            // 返回订单状态信息
            Map<String, Object> statusInfo = new HashMap<>();
            statusInfo.put("orderNo", orderNo);
            statusInfo.put("payStatus", order.getPayStatus());
            statusInfo.put("orderStatus", order.getOrderStatus());
            statusInfo.put("payType", order.getPayType());
            statusInfo.put("payTime", order.getPayTime());
            statusInfo.put("amount", order.getAmount());
            statusInfo.put("payAmount", order.getPayAmount());
            statusInfo.put("expireTime", order.getExpireTime());
            statusInfo.put("createdTime", order.getCreatedTime());
            statusInfo.put("isDeleted", order.getIsDeleted());
            
            return Result.success(statusInfo);
            
        } catch (Exception e) {
            log.error("查询订单状态失败，订单号：{}", orderNo, e);
            return Result.fail("查询订单状态失败");
        }
    }
    
    /**
     * 客户端删除订单（软删除）
     */
    @DeleteMapping("/delete/{orderNo}")
    public Result<?> deleteOrderByUser(@PathVariable String orderNo) {
        log.info("客户端删除订单，订单号：{}", orderNo);
        try {
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.fail("订单号不能为空");
            }
            
            // 验证订单是否存在
            CourseOrder order = courseOrderService.getByOrderNo(orderNo);
            if (order == null) {
                return Result.fail("订单不存在");
            }
            
            // 检查是否已经删除
            if (order.getIsDeleted() != null && order.getIsDeleted()) {
                return Result.fail("订单已删除");
            }
            
            // 调用软删除服务
            boolean success = courseOrderService.softDeleteOrder(orderNo);
            if (success) {
                log.info("客户端删除订单成功，订单号：{}", orderNo);
                return Result.success("删除订单成功");
            } else {
                log.error("客户端删除订单失败，订单号：{}", orderNo);
                return Result.fail("删除订单失败");
            }
            
        } catch (Exception e) {
            log.error("客户端删除订单异常，订单号：{}", orderNo, e);
            return Result.fail("删除订单失败");
        }
    }
    /**
     * 根据条件查询订单
     */
    @PostMapping("/selectCount")
    public Result<?> searchOrdersCount(@RequestBody CourseOrder order) {
        log.info("根据条件查询订单：" + order);
        try {
            if (order == null || order.getPageNum() == null || order.getPageSize() == null){
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (order.getPageNum() <= 0 || order.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }

            // 强制只查询未删除的订单，忽略前端传入的 isDeleted 参数
            order.setIsDeleted(false);

            return courseOrderService.getByConditionWithCourseCount(order);
        } catch (Exception e) {
            log.info("查询订单信息失败",e);
            return Result.fail("查询订单信息失败");
        }
    }

    @GetMapping("/detail/{orderNo}")
    public Result<?> getOrderDetail(@PathVariable String orderNo) {
        log.info("查询订单详情，订单号：{}", orderNo);
        try {
            return courseOrderService.getOrderDetail(orderNo);
        }
        catch (Exception e) {
            log.error("查询订单详情失败，订单号：{}", orderNo, e);
            return Result.fail("查询订单详情失败");
        }
    }

}
